package cloudContact.servlet;

import java.io.IOException;
import java.util.Scanner;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.GoogleApi;
import org.scribe.model.Token;
import org.scribe.oauth.OAuthService;

import cloudContact.GoogleConstant;
import cloudContact.MyDAOException;
import cloudContact.SecurityManager;
import cloudContact.DAO.User;
import cloudContact.DAO.UserDAO;

import com.google.gdata.client.authn.oauth.*;

/**
 * Servlet implementation class GoogleOAuth
 */
@WebServlet("/GoogleOAuth")
public class GoogleOAuth extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GoogleOAuth() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 * @see http://code.google.com/apis/gdata/docs/auth/oauth.html#Examples
	 * 
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Start GoogleOAuth...");

		try {
			if (!SecurityManager.CheckAuthorization(request)) {
				System.out.println("Error: User is not authorized.");
				return;
			}
		} catch (RollbackException e1) {
			e1.printStackTrace();
		} catch (MyDAOException e1) {
			e1.printStackTrace();
		}
		
		HttpSession session = request.getSession();
		
		OAuthService service = GoogleConstant.getOAuthService();

		// Obtain the Request Token
		System.out.println("Fetching the Request Token...");
		Token requestToken = service.getRequestToken();
		
		try {			
			User user = UserDAO.getInstance().lookup(session.getAttribute("userId").toString());
			user.setGMailAccessToken(requestToken.getToken());
			user.setGMailAuthSecrete(requestToken.getSecret());					
			UserDAO.getInstance().update(user);
			
		} catch (RollbackException e) {
			e.printStackTrace();
		} catch (MyDAOException e) {
			e.printStackTrace();
		}
		
		String urlWithSessionID = response.encodeRedirectURL(GoogleConstant.AUTHORIZE_URL + requestToken
				.getToken());
		response.sendRedirect(urlWithSessionID);

		System.out.println("Finish GoogleOAuth");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
